<?php

namespace App\Dao\User;

use App\Dao\Task\TaskDao;
use Hyperf\DbConnection\Db;
use Yj\Daos\BaseDao;
use App\Model\User\UserMoney;
use Hyperf\Database\Model\Builder;
use Yj\Daos\Verify;
use Hyperf\Utils\Collection;

/**
 * @var UserMoney
 */
class UserMoneyDao extends BaseDao
{
    public function DaoWhere(array $params)
    {

        return $this->getDaoQuery($params, function (Verify $verify) {
            $verify("id", function (Builder $query, $id) {
                $query->where("id", $id);
            });
        });

    }

    public function addTaskLog($taskId, $userId)
    {
        $taskDao = App(TaskDao::class)->DaoWhere(['id' => $taskId])->firstOrError();
        $number = $taskDao->one_price;
        $title = '完成任务';
        $type = 'task';
        $link_id = $taskId;
        $pm = 1;
        $this->addLog($userId, $number, $title, $type, $link_id, $pm);
        return true;
    }

    private function addLog($uid, mixed $number, string $title, string $type, $link_id, int $pm)
    {
        Db::beginTransaction();
        try {
            $userDao = App(UserDao::class)->where('uid', $uid)->firstOrError();
//            $userDao->now_money += $number;
            $this->add(_Collect([
                'balance' => $userDao->integral,
                'user_id' => $uid,
                'link_id' => $link_id,
                'type' => $type,
                'title' => $title,
                'pm' => $pm,
                'number' => $number,
                'status' => 1,
            ]));
            App(UserDao::class)->opAccount('integral', $uid, $number, 'task_settlement');
//            $userDao->save();
            Db::commit();
        } catch (\Exception $exception) {
            Db::rollBack();
            _Exception($exception->getMessage());
        }
        return true;
    }


    public function lists(Collection $params)
    {

        $data = $this->DaoWhere($params->toArray())->orderByDesc("id")->getList();
        return $data;

    }

    public function add(Collection $params)
    {
        $data = $this->create($params->toArray());
        return $data;

    }

    public function del(int $id)
    {

        $data = $this->DaoWhere(["id" => $id])->firstOrError();
        return $data->delete();

    }


}
